package com.alphas.aivergil.persistant;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import jakarta.annotation.Resource;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 持久化聊天记忆存储实现
 * 使用MySQL数据库和MyBatis-Plus框架实现聊天记忆的持久化存储
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PersistentChatMemoryStore implements ChatMemoryStore {

    public static final String CHAT_MEMORY_PREFIX = "CHAT_MEMORY:";

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<ChatMessage> getMessages(Object sessionId) {
        String value = redisTemplate.opsForValue().get(CHAT_MEMORY_PREFIX + sessionId);
        return ChatMessageDeserializer.messagesFromJson(value);
    }

    @Override
    public void updateMessages(Object sessionId, List<ChatMessage> messages) {
        redisTemplate.opsForValue().set(CHAT_MEMORY_PREFIX + sessionId, ChatMessageSerializer.messagesToJson(messages));
    }

    @Override
    public void deleteMessages(Object sessionId) {
        log.debug("删除会话消息, sessionId: {}", sessionId);
        redisTemplate.delete(CHAT_MEMORY_PREFIX + sessionId);
    }
}
